package com.imooc.miaosha.service;

import com.imooc.miaosha.domian.MiaoShaOrder;
import com.imooc.miaosha.domian.OrderInfo;
import com.imooc.miaosha.domian.User;
import com.imooc.miaosha.redis.keys.MiaoshaKey;
import com.imooc.miaosha.redis.RedisFactory;
import com.imooc.miaosha.util.Md5Utils;
import com.imooc.miaosha.util.UuidUtils;
import com.imooc.miaosha.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Random;

/**
 * 模块描述: <br>
 * ()
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/19 10:50
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
public class MiaoShaService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisFactory redisFactory;

    public void reset(List<GoodsVO> goodsList) {
        goodsService.resetStock(goodsList);
        orderService.deleteOrders();
    }

    @Transactional(rollbackFor = Exception.class)
    public OrderInfo miaoSha(User user, GoodsVO goodsVo) {
        // 扣库存
        boolean flag = goodsService.reduceStock(goodsVo);
        if (flag) {
            // 创建订单
            OrderInfo orderInfo = orderService.createOrder(user, goodsVo);
            return orderInfo;
        } else {
            setGoodsOver(goodsVo.getId());
            return null;
        }
    }


    public long getMiaoshaResult(Long userId, long goodsId) {
        MiaoShaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        if (order != null) {
            return order.getOrderId();
        } else {
            boolean flag = getGoodsOver(goodsId);
            if (flag) {
                return -1;
            } else {
                return 0;
            }
        }
    }

    private boolean getGoodsOver(long goodsId) {
        return redisFactory.exists(MiaoshaKey.isGoodsOver, "" + goodsId);
    }

    private void setGoodsOver(Long goodsId) {
        redisFactory.set(MiaoshaKey.isGoodsOver, "" + goodsId, true);
    }

    public String createMiaoshaPath(User user, long goodsId) {
        String str = Md5Utils.md5(UuidUtils.uuid() + "12345");
        MiaoshaKey miaoshaKey = MiaoshaKey.getMiaoshaPath;
        miaoshaKey.setExpireSeconds(60);
        redisFactory.set(miaoshaKey, "" + user.getId() + ":" + goodsId, str);
        return str;
    }

    public boolean checkPath(User user, Long goodsId, String path) {
        String code = redisFactory.get(MiaoshaKey.getMiaoshaPath, "" + user.getId() + ":" + goodsId, String.class);
        if (!StringUtils.isEmpty(path) && !StringUtils.isEmpty(code) && code.equals(path)) {
            return true;
        }
        return false;
    }

    public BufferedImage createVerifyCode(User user, long goodsId) {
        if (user == null || goodsId <= 0) {
            return null;
        }
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        MiaoshaKey miaoshaKey = MiaoshaKey.getMiaoshaVerifyCode;
        miaoshaKey.setExpireSeconds(300);
        redisFactory.set(miaoshaKey, user.getId() + "," + goodsId, rnd);
        //输出图片
        return image;
    }


    public boolean checkVerifyCode(User user, long goodsId, int verifyCode) {
        Integer code = redisFactory.get(MiaoshaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, Integer.class);
        if (user != null && goodsId > 0 && verifyCode == code) {
            redisFactory.delete(MiaoshaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId);
            return true;
        }
        return false;
    }

    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer) engine.eval(exp);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    private static char[] ops = new char[]{'+', '-', '*'};

    /**
     * + - *
     */
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = "" + num1 + op1 + num2 + op2 + num3;
        return exp;
    }

}
